package com.qls.ali.biz.service.fz.impl;


import com.qls.ali.biz.data.util.FzUtil;
import com.qls.ali.biz.service.fz.Cache;
import com.qls.ali.biz.service.fz.RatesService;
import com.qls.core.dto.HtDailyRoom;
import com.qls.core.entity.DtStore;
import com.qls.core.entity.OpOurRateplanPrice;
import com.qls.core.utils.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author yunchao
 */
@Service
@Slf4j
public class RatesServiceImpl implements RatesService {
    private final Pattern pattern = Pattern.compile("rpcode=(\\w+)未查询到");

    @Autowired
    private Cache cache;

    @Override
    public void pushBatch(Map<Long, List<HtDailyRoom>> map, Integer storeId) {
        DtStore dtStore = cache.getStore(storeId);
        if (Objects.isNull(dtStore)) {
            log.warn("价格增量推送，店铺id：{} 缓存不存在", storeId);
            return;
        }
        Map<String, List<HtDailyRoom>> stringListMap = new HashMap<>();
        List<String> zeroDates = cache.getZeroDate(storeId);
        for (Long k : map.keySet()) {
            // 查询店铺缓存 下rp推送的roomCode和自定义rp的id
            Map<String, Object> rpStoreMap = cache.getRpStoreMap(k.toString(), storeId);
            if (rpStoreMap.isEmpty()) {
                continue;
            }
            String roomCode = (String) rpStoreMap.get("roomCode");
            List<Integer> crpIds = (List<Integer>) rpStoreMap.get("crpIds");
            // 批量查询缓存价态
            List<HtDailyRoom> htDailyRooms = map.get(k);
            for (Integer crpId : crpIds) {
                List<OpOurRateplanPrice> opOurRateplanPriceList = cache.getStairPrice(crpId);
                List<HtDailyRoom> htDailyRoomList = new ArrayList<>();
                for (HtDailyRoom htDailyRoom : htDailyRooms) {
                    Integer price = htDailyRoom.getPrice();
                    Integer status = htDailyRoom.getStatus();
                    String date = htDailyRoom.getDate();
                    if (!zeroDates.isEmpty()) {
                        if (zeroDates.contains(date)) {
                            htDailyRoom.setSaleNum(0);
                        }
                    }
                    if (Objects.isNull(price) || status.equals(0)) {
                        htDailyRoom.setSaleNum(0);
                    } else {
                        for (OpOurRateplanPrice opOurRateplanPrice : opOurRateplanPriceList) {
                            Integer changePriceStart = opOurRateplanPrice.getChangePriceStart();
                            Integer changePriceEnd = opOurRateplanPrice.getChangePriceEnd();
                            Integer highestPrice = opOurRateplanPrice.getHighestPrice();
                            if (price >= changePriceStart && price < changePriceEnd) {
                                price = price * (100 + opOurRateplanPrice.getChargePricePercent()) / 100 + opOurRateplanPrice.getChargePriceAmount();
                                if (price >= highestPrice) {
                                    price = highestPrice;
                                }
                                htDailyRoom.setPrice(price);
                                break;
                            }
                        }
                    }
                    htDailyRoomList.add(htDailyRoom);
                }
                stringListMap.put(k + "qls" + crpId + "_" + roomCode, htDailyRoomList);
            }
        }
        if (stringListMap.isEmpty()) {
            return;
        }
        List<Map<String, List<HtDailyRoom>>> mapList;
        int maxNum = 20;
        if (stringListMap.size() <= maxNum) {
            mapList = new ArrayList<>();
            mapList.add(stringListMap);
        } else {
            // map 拆分最大size 30
            mapList = MapUtil.mapChunk(stringListMap, maxNum);
        }
        for (Map<String, List<HtDailyRoom>> mapCut : mapList) {
            String result = FzUtil.pushRates(mapCut, dtStore.getAppKey(), dtStore.getSessionKey(), dtStore.getSecret());
            if (result.contains("rate解析结果为空")) {
                log.warn("rate解析结果为空" + result);
                this.cleanCache(result, storeId);
                return;
            }
            if (result.contains("error_response")) {
                log.warn("rates推送异常:{}，异常信息：{}", mapCut.keySet(), result);
            }
        }
    }

    /**
     * 清理垃圾缓存rp
     *
     * @param result  String
     * @param storeId Integer
     */
    private void cleanCache(String result, Integer storeId) {
        Matcher m = pattern.matcher(result);
        List<String> strings = new ArrayList<>();
        while (m.find()) {
            strings.add(m.group(1));
        }
        Map<String, List<Integer>> map = new HashMap<>();
        for (String s : strings) {
            String[] newStr = s.split("qls");
            String rpCode = newStr[0];
            Integer id = Integer.valueOf(newStr[1]);
            List<Integer> crpIds;
            crpIds = map.get(rpCode);
            if (Objects.isNull(crpIds)) {
                crpIds = new ArrayList<>();
                crpIds.add(id);
            } else {
                if (crpIds.contains(id)) {
                    continue;
                }
                crpIds.add(id);
            }
            map.put(rpCode, crpIds);
        }
        for (String rpCode : map.keySet()) {
            List<Integer> crpIds = map.get(rpCode);
            cache.delRpStoreMap(rpCode, storeId, crpIds);
        }
        log.info("清理垃圾rp缓存：{}", strings);
    }
}
